<template>
  <div>
    <h2>评论管理</h2>

    <!-- 评论表格 -->
    <table>
      <thead>
      <tr>
        <th>评论ID</th>
        <th>用户ID</th>
        <th>车辆ID</th>
        <th>评分</th>
        <th>评价内容</th>
        <th>评价时间</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="review in reviews" :key="review.reviewId">
        <td>{{ review.reviewId }}</td>
        <td>{{ review.userId }}</td>
        <td>{{ review.productId }}</td>
        <td>{{ review.rating }}</td>
        <td>{{ review.reviewText }}</td>
        <td>{{ review.reviewDate }}</td>
        <td>
          <button @click="deleteReview(review.reviewId)">删除</button>
        </td>
      </tr>
      </tbody>
    </table>

    <!-- 分页组件 -->
    <Pagination
        :current-page="currentPageNumber"
        :total="totalReviews"
        :page-size="pageSize"
        @update:currentPage="handlePageChange"
    />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import Pagination from '@/components/Pagination.vue';
import axios from 'axios';

export default {
  components: {
    Pagination,
  },
  props: {
    currentPageNumber: {
      type: Number,
      required: true,
    },
    pageSize: {
      type: Number,
      required: true,
    },
  },
  setup(props, { emit }) {
    const reviews = ref([]);
    const totalReviews = ref(0);
    const deleteReview = async (reviewId) => {
      try {
        // 向后端发送删除请求
        await axios.post('admins/deleteReview', { reviewId });
        // 删除成功后重新获取评论数据
        fetchReviews(props.currentPageNumber, props.pageSize);
      } catch (error) {
        console.error('Failed to delete review:', error);
      }
    };


    // 请求评论数据
    const fetchReviews = async (pageNum, pageSize) => {
      try {
        const response = await axios.post('admins/selectAllReviews', {
          pageNum,
          pageSize,
        });
        reviews.value = response.data.records;
        totalReviews.value = response.data.total;
      } catch (error) {
        console.error('Failed to fetch reviews:', error);
      }
    };

    // 处理分页更改
    const handlePageChange = (newPage) => {
      emit('update:currentPageNumber', newPage);
      fetchReviews(newPage, props.pageSize);
    };

    // 初始化时加载评论数据
    fetchReviews(props.currentPageNumber, props.pageSize);

    return {
      reviews,
      totalReviews,
      handlePageChange,
      deleteReview
    };
  },
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

table th,
table td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: left;
}
</style>
